-------------
-- Vertigo --
-------------

gVertigo_Settings = nil
gVertigo_GlobalSettings = nil

-- this is our addon object (thanks to Clahaire and his TomTom mod)
Vertigo = {
    events = {},
    eventFrame = CreateFrame("Frame"),
    RegisterEvent = function(self, event, method)
        self.eventFrame:RegisterEvent(event)
        self.events[event] = method or event
    end,
    UnregisterEvent = function(self, event)
        self.eventFrame:UnregisterEvent(event)
        self.events[event] = nil
    end,
}

Vertigo.eventFrame:SetScript("OnEvent", function(self, event, ...)
    local method = Vertigo.events[event]
    if method and Vertigo[method] then
        Vertigo[method](Vertigo, event, ...)
    end
end)

Vertigo:RegisterEvent("ADDON_LOADED")

function pm(m)
    DEFAULT_CHAT_FRAME:AddMessage(m)
end

function Vertigo:ADDON_LOADED(event, addon)
    if addon == "Vertigo" then
        self:UnregisterEvent("ADDON_LOADED")
        -- do loading stuff
        self.defaults = {
            totalDamage = 0,
            worstDamage = 0,
        }
        
        local realmName = GetRealmName()
        local charName = UnitName("player")
        
        gVertigo_GlobalSettings = gVertigo_GlobalSettings or {}
        
        self.realmSettings = gVertigo_GlobalSettings[realmName] or {}
        gVertigo_GlobalSettings[realmName] = self.realmSettings
        
        self.settings = self.realmSettings[charName] or self.defaults -- XXX safe?
        self.realmSettings[charName] = self.settings
        
        self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED", "CombatLogEvent")
    end
end

function Vertigo:CombatLogEvent(event, timestamp, eventtype, ...)
    if eventtype == "ENVIRONMENTAL_DAMAGE" then
        self:EnvironmentalDamage(timestamp, eventtype, ...)
    end
end

function Vertigo:EnvironmentalDamage(timestamp, eventtype, srcGUID, srcName, srcFlags, destGUID, destName, destFlags, env_type, amount, school, resisted, blocked, absorbed, critical, glancing, crushing)
    if env_type == "FALLING" and bit.band(destFlags, 0xFF0F) == 0x0501 then
        self.settings.totalDamage = amount + self.settings.totalDamage
        self.settings.worstDamage = max(amount, self.settings.worstDamage)
        DEFAULT_CHAT_FRAME:AddMessage(format("You took %d falling damage! (%d total, %d worst ever)", amount, self.settings.totalDamage, self.settings.worstDamage), 1, 0, 0)
    end
end